package com.estudy.contorller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.estudy.entity.Course;
import com.estudy.entity.Knowledge;
import com.estudy.entity.ResultVo;
import com.estudy.service.CourseService;
import com.estudy.service.FileService;
import com.google.common.collect.Maps;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * @author: sun.hongliang
 * @create: 2019/09/05 15:15
 */
@Controller
@RequestMapping("/course")
public class CourseController {
    private static final Logger logger = Logger.getLogger(CourseController.class);
    @Autowired
    private CourseService courseService;
    @Autowired
    private FileService fileService;

    @RequestMapping("/chapterPage")
    public ModelAndView addChapterPage(String id, String chapterName, String courseName) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("course/chapter-info");
        modelAndView.addObject("id", id);
        modelAndView.addObject("chapterName", chapterName);
        modelAndView.addObject("courseName", courseName);
        List<Knowledge> knowledges = fileService.queryAllFiles();
        Set<String> selectFiledById = courseService.querySelectFiledById(id);
        List<Knowledge> selectKnowledges = new ArrayList<Knowledge>();
        List<Knowledge> noSelectKnowledges = new ArrayList<Knowledge>();
        for (Knowledge k : knowledges) {
            if (k.getApproval() != 1) {
                continue;
            }
            if (!selectFiledById.contains(k.getFid())) {
                noSelectKnowledges.add(k);
            } else {
                selectKnowledges.add(k);
            }
        }
        modelAndView.addObject("selectKnowledges", selectKnowledges);
        modelAndView.addObject("noSelectKnowledges", noSelectKnowledges);
        return modelAndView;
    }

    @RequestMapping("/listPage")
    public ModelAndView courseListPage() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("course/course-list");
        return modelAndView;
    }


    @RequestMapping("/addPage")
    public ModelAndView courseAddPage() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("course/course-add");
        return modelAndView;
    }

    @RequestMapping("/dataList")
    @ResponseBody
    public String queryCourseData() {
        try {
            Map<String, Object> map = Maps.newHashMap();
            List<Course> courses = courseService.queryAllCourses();
            map.put("data", courses);
            map.put("recordsTotal", courses.size());
            map.put("recordsFiltered", courses.size());
            map.put("pageNum", 1);
            return JSON.toJSONString(map, SerializerFeature.WriteMapNullValue);
        } catch (Exception e) {
            logger.error("queryCourseData error", e);
        }
        return "";
    }


    @RequestMapping("/add")
    @ResponseBody
    public String courseAdd(@ModelAttribute Course course, String courseStatus) {
        ResultVo resultVo = new ResultVo();
        try {
            if ("ON".equalsIgnoreCase(courseStatus) || "上架".equals(courseStatus)) {
                course.setStatus(1);
            } else {
                course.setStatus(0);
            }
            course.setCid(UUID.randomUUID().toString().replaceAll("-", ""));
            course.setCreateTime(System.currentTimeMillis());
            course.setChapter(1);
            courseService.addCourse(course);
            resultVo.setStatus(200);
            resultVo.setMessage("SUCCESS");
        } catch (Exception e) {
            logger.error("courseAdd error", e);
            resultVo.setStatus(500);
            resultVo.setMessage("保存失败");
        }
        return JSON.toJSONString(resultVo, SerializerFeature.WriteMapNullValue);
    }

    @RequestMapping("/del")
    @ResponseBody
    public String courseDel(String id) {
        ResultVo resultVo = new ResultVo();
        try {
            courseService.deleteCourseById(id);
            resultVo.setStatus(200);
            resultVo.setMessage("删除成功");
        } catch (Exception e) {
            logger.error("courseDel error", e);
            resultVo.setStatus(500);
            resultVo.setMessage("删除失败");
        }
        return JSON.toJSONString(resultVo, SerializerFeature.WriteMapNullValue);
    }

    @RequestMapping("/chapterCourseMap")
    @ResponseBody
    public String chapterCourseMap(String id, String fids) {
        ResultVo resultVo = new ResultVo();
        try {
            List<String> fidList = new ArrayList<String>();
            if (!StringUtils.isEmpty(fids)) {
                String[] fidStringArray = fids.split(",");
                fidList = Arrays.asList(fidStringArray);
            }
            courseService.addChapterCourseMap(id, fidList);
            resultVo.setStatus(200);
            resultVo.setMessage("设置内容成功");
        } catch (Exception e) {
            logger.error("chapterCourseMap error", e);
            resultVo.setStatus(500);
            resultVo.setMessage("设置内容失败");
        }
        return JSON.toJSONString(resultVo, SerializerFeature.WriteMapNullValue);
    }

    @RequestMapping("/addChapter")
    @ResponseBody
    public String courseAddChapter(String cid) {
        ResultVo resultVo = new ResultVo();
        try {
            courseService.addChapter(cid);
            resultVo.setStatus(200);
            resultVo.setMessage("添加成功");
        } catch (Exception e) {
            logger.error("courseAddChapter error", e);
            resultVo.setStatus(500);
            resultVo.setMessage("添加失败");
        }
        return JSON.toJSONString(resultVo, SerializerFeature.WriteMapNullValue);
    }
}
